package as3.component.controls
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	import as3.component.Component;
	
	public class TabBar extends Component
	{
		
		protected var list:Array = [];
		
		protected var _selectedIndex:uint = 0;
		
		public function TabBar()
		{
			super(false);
//			setMasked(true);
		}
		
		/**
		 *输入Tab列表 
		 * @param value   [String, String, String]
		 * 
		 */		
		public function set tabList(value:Array):void
		{
			if (!value || value.length == 0) return;
			
			for (var i:int = 0; i < value.length; i++)
			{
				var tabBtn:TabButton = new TabButton(String(value[i]));
				tabBtn.addEventListener(Event.CHANGE, $onTabChangeHandler);
				list[i] = tabBtn;
			}
			updateLayoutBtn();
			list[0].selected = true;
		}
		
		protected function updateLayoutBtn():void
		{
			var w:Number = 0;
			var h:Number = 0;
			var btn:TabButton;
			for (var i:int = 0; i < list.length; i++)
			{
				btn = list[i];
				btn.x = w;
				w += btn.width;
				h = btn.height > h ? btn.height : h;
				addChild(btn as DisplayObject);
			}
			this.width=w;
			this.height=h
//			setMaskRect(new IntRectangle(0,0,w, h));
		}
		
		public function set selectedIndex(value:uint):void
		{
			if (value < list.length && value != selectedIndex) {
				_selectedIndex = value;
				selectBtn(list[selectedIndex] as TabButton);
			}
		}
		
		public function get selectedIndex():uint
		{
			return _selectedIndex;
		}
		
		protected function $onTabChangeHandler(evt:Event):void
		{
			var btn:TabButton = evt.currentTarget as TabButton;
			selectBtn(btn, true);
		}
		
		private function selectBtn(btn:TabButton, fromClick:Boolean = false):void
		{
			var index:uint = 0;
			var i:int
			for (i = 0; i < list.length; i++)
			{
				if(list[i] == btn) {
					index = i;
					break;
				}
			}
			if (fromClick) {
				if (selectedIndex == index) return;
				_selectedIndex = index;
			}
			for (i = 0; i < list.length; i++)
			{
				if(i != index) {
					list[i].unSelected();
				}
			}
			if(!fromClick) {
				list[selectedIndex].selected = true;
			}
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		public function setTabButtonSize(w:Number, h:Number):void
		{
			for (var i:int = 0; i < list.length; i++)
			{
				list[i].width = w;
				list[i].height = h;
			}
			updateLayoutBtn();
		}
		
		public function getTabButtonByIndex(index:int):TabButton
		{
			if (index >= list.length) return null;
			return list[index];
		}
	}
}